package com.na.tools.ping.impl;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import com.na.tools.CommonTools;
import com.na.tools.ping.NetworkChecker.BatchNetworkChecker;

public class CommondNetworkChecker extends BatchNetworkChecker {

	@Override
	public long connect(String host) {
		Process p = null;
		InputStream in = null;
		try {
			p = Runtime.getRuntime().exec("ping -w 3000 " + host);
			p.waitFor();
			in = p.getInputStream();
			ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
			byte[] b = new byte[8];
			int len;
			while ((len = in.read(b)) != -1) {
				buf.write(b, 0, len);
			}
			return parseResult(new String(buf.toByteArray(), System.getProperty("sun.jnu.encoding")));
		} catch (Exception e) {
		} finally {
			CommonTools.closeIO(in);
			if (p != null) {
				p.destroy();
			}
		}
		return Long.MAX_VALUE;
	}
	
	private static long parseResult(String result) {
//		最短 = 3ms，最长 = 10ms，平均 = 4ms
		if (result == null || result.length() == 0 ) {
			return Long.MAX_VALUE;
		}
		int dot = result.lastIndexOf('=');
		if (dot < 0) {
			return Long.MAX_VALUE;
		}
		int dot2 = result.indexOf("ms", dot);
		if (dot2 < 0) {
			return Long.MAX_VALUE;
		}
		String time = result.substring(dot + 1, dot2);
		return Integer.parseInt(time.trim());
	}

}
